#!/bin/bash

# path
# 使用 hostname 在 MBP 上一直获取的是 localhost
if [ $(scutil --get LocalHostName) = "marcowdeiMac" ];then
    OpS_PATH='/Volumes/T4/OpS'
    MN_IDA_DEST="/Volumes/Other/Study/Develop/Debug/DebugTest/MarginNote3/3.7.11"
elif [ $(scutil --get LocalHostName) = "MBP" ];then 
    OpS_PATH="${HOME}/OpS"
    MN_IDA_DEST="${HOME}/Desktop/DebugTest/MN3/3.7.11"
else
    echo "⚠️  ⚠️  ⚠️  主机名错误！！！ ⚠️  ⚠️  ⚠️"
    exit 68 # EX_NOHOST
fi


IDA_APP="/Applications/IDA Pro 7.0/ida64.app"
MN_IDA="MarginNote 3.i64"
MN_IDA_ZIP="${MN_IDA}.zip"
TMP_PATH="/private/tmp"

RepositoryPaths=(
    "${OpS_PATH}/Debug/DebugStudyDemo"
    "${OpS_PATH}/Debug/TinyToolsSwift"
    "${OpS_PATH}/My/logseq"
    "${OpS_PATH}/My/Note"
    "${OpS_PATH}/My/NoteProject/PDF/APDF"
    )
MN_IDA_SOUR=${HOME}/Library/Mobile\ Documents/com\~apple\~CloudDocs

END="============================="

# git pull
for path in "${RepositoryPaths[@]}"; do
    pushd "${path}"
    git pull

    # 应用补丁
    status=`git status -s`
    name=${path##*/}
    patchFile="${MN_IDA_SOUR}/${name}.patch"
    
    if [ -f "${patchFile}" ]; then
        if [ -n "${status}" ]; then
            echo "⚠️  ⚠️  ⚠️  git: ${path} 有修改, 无法打补丁！！！ ⚠️  ⚠️  ⚠️"
            open /Applications/Tower.app
        else
            error_filename="git_patch_error"
            error_path="${TMP_PATH}/${error_filename}"
            echo "">"${error_path}"
            git apply --check "${patchFile}" 2>"${error_path}"
            content=$(cat ${error_path})
            if [ -n "${content}" ]; then
                echo "⚠️  ⚠️  ⚠️  git: ${path} 应用补丁错误！！！ ⚠️  ⚠️  ⚠️"
                echo "${content}"
            else
                git apply "${patchFile}"
                echo "📡 📡 📡 ️ git patched: ${path} 📡 📡 📡 ️️"
                bak_path="${TMP_PATH}/GitPatch/"
                mkdir "${bak_path}"
                mv "${patchFile}" "${bak_path}"
            fi
        fi 
    fi
    
    popd
    echo "${path} pull complete!"
done
echo ${END}


# move ida file
pushd "${MN_IDA_DEST}"

zipFile="${MN_IDA_SOUR}/${MN_IDA_ZIP}"

if [ -f "${zipFile}" ]; then
    # close ida
    osascript -e 'quit app "ida64"'

    mv "${zipFile}" "./"
    echo "MN_IDA moved!"
    echo ${END}
    time=$(date "+%Y%m%d%H%M%S")
    mv "./${MN_IDA}" "./${MN_IDA}-${time}"

    # unzip
    unzip "./${MN_IDA_ZIP}"
    rm "./${MN_IDA_ZIP}"
    open -a "${IDA_APP}" "${MN_IDA_DEST}/${MN_IDA}"
    echo ${END}
else
    echo "📡 📡 📡 ️ 没有文件：${zipFile} 📡 📡 📡 ️️" 
    echo ${END}
fi

popd
